package com.frxuexi.park2209.mynews

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.base.entity.MyNewsBean
import com.frxuexi.base.entity.MyNewsBeanItem
import com.frxuexi.base.net.ApiService
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class MyNewsDataSource(val apiService: ApiService):PagingSource<Int,MyNewsBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, MyNewsBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MyNewsBeanItem> {
        return try {
            val page=params.key?:0
            val map = mapOf<String, Int>("page" to page)
            val json = Gson().toJson(map)
            val body = RequestBody.create("application/json".toMediaTypeOrNull(), json)
            val news = apiService.getAllNews(body)
            val newsBean = Gson().fromJson(news.values, MyNewsBean::class.java)
                .filter {
                    it.newsTitle!="string" && !it.newsTitle.isNullOrEmpty()
                }
            val nextPage=if(newsBean!=null) page+1 else null
            val prePage=if(page>0) page-1 else null
            LoadResult.Page(newsBean,prePage,nextPage)
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }

}